using System;
using System.Collections.Generic;
using System.Linq;
using TangCaptureTraffic.Models;
using Fiddler;

namespace TangCaptureTraffic.Services
{
    /// <summary>
    /// UI服务实现类，负责UI相关的操作和数据绑定
    /// </summary>
    public class UIService : IUIService
    {
        private readonly ISessionService _sessionService;
        private readonly IDataFormattingService _dataFormattingService;
        private readonly ISessionFormattingService _sessionFormattingService;
        private readonly IConfigurationService _configurationService;

        public UIService(
            ISessionService sessionService,
            IDataFormattingService dataFormattingService,
            ISessionFormattingService sessionFormattingService,
            IConfigurationService configurationService)
        {
            _sessionService = sessionService ?? throw new ArgumentNullException(nameof(sessionService));
            _dataFormattingService = dataFormattingService ?? throw new ArgumentNullException(nameof(dataFormattingService));
            _sessionFormattingService = sessionFormattingService ?? throw new ArgumentNullException(nameof(sessionFormattingService));
            _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));

            // 订阅会话服务事件
            _sessionService.SessionAdded += OnSessionAdded;
            _sessionService.SessionCompleted += OnSessionCompleted;
        }

        /// <summary>
        /// 会话添加事件
        /// </summary>
        public event EventHandler<SessionModel> SessionAdded;

        /// <summary>
        /// 会话更新事件
        /// </summary>
        public event EventHandler<SessionModel> SessionUpdated;

        /// <summary>
        /// 会话清理事件
        /// </summary>
        public event EventHandler SessionsCleared;

        /// <summary>
        /// 内存状态更新事件
        /// </summary>
        public event EventHandler<MemoryStatusEventArgs> MemoryStatusUpdated;

        /// <summary>
        /// 将Fiddler会话转换为UI显示模型
        /// </summary>
        /// <param name="session">Fiddler会话对象</param>
        /// <returns>UI显示模型</returns>
        public SessionModel ConvertToSessionModel(Session session)
        {
            if (session == null) return null;

            return new SessionModel
            {
                Flagname = session["flagname"],
                Index = session.id,
                Id = session.id.ToString(),
                Url = session.fullUrl,
                Method = session.RequestMethod,
                StatusCode = session.responseCode,
                Host = session.hostname,
                ContentType = GetContentType(session),
                ResponseSize = GetResponseSize(session),
                ResponseTime = GetResponseTime(session),
                RequestTime = GetRequestTime(session),
                Session = session
            };
        }

        /// <summary>
        /// 批量转换Fiddler会话为UI显示模型
        /// </summary>
        /// <param name="sessions">Fiddler会话列表</param>
        /// <returns>UI显示模型列表</returns>
        public List<SessionModel> ConvertToSessionModels(IEnumerable<Session> sessions)
        {
            if (sessions == null) return new List<SessionModel>();

            return sessions.Select(ConvertToSessionModel).Where(model => model != null).ToList();
        }

        /// <summary>
        /// 更新内存状态显示
        /// </summary>
        /// <param name="usedMemory">已使用内存（MB）</param>
        /// <param name="sessionCount">会话数量</param>
        public void UpdateMemoryStatus(double usedMemory, int sessionCount)
        {
            var threshold = _configurationService.GetMemoryWarningThreshold();
            var isWarning = usedMemory > threshold;

            var args = new MemoryStatusEventArgs
            {
                UsedMemory = usedMemory,
                SessionCount = sessionCount,
                IsWarning = isWarning,
                Message = isWarning ? $"内存使用过高: {usedMemory:F1}MB (阈值: {threshold}MB)" : null
            };

            MemoryStatusUpdated?.Invoke(this, args);
        }

        /// <summary>
        /// 显示内存警告
        /// </summary>
        /// <param name="message">警告消息</param>
        public void ShowMemoryWarning(string message)
        {
            var args = new MemoryStatusEventArgs
            {
                IsWarning = true,
                Message = message
            };

            MemoryStatusUpdated?.Invoke(this, args);
        }

        /// <summary>
        /// 应用过滤器
        /// </summary>
        /// <param name="filterText">过滤文本</param>
        /// <param name="sessions">会话列表</param>
        /// <returns>过滤后的会话列表</returns>
        public List<SessionModel> ApplyFilter(string filterText, IEnumerable<SessionModel> sessions)
        {
            if (string.IsNullOrWhiteSpace(filterText) || sessions == null)
            {
                return sessions?.ToList() ?? new List<SessionModel>();
            }

            var filter = filterText.ToLower();
            return sessions.Where(session =>
                session.Url?.ToLower().Contains(filter) == true ||
                session.Host?.ToLower().Contains(filter) == true ||
                session.Method?.ToLower().Contains(filter) == true ||
                session.StatusCode.ToString().Contains(filter) ||
                session.ContentType?.ToLower().Contains(filter) == true
            ).ToList();
        }

        /// <summary>
        /// 获取选中的会话详情
        /// </summary>
        /// <param name="sessionModel">选中的会话模型</param>
        /// <returns>会话详情文本</returns>
        public string GetSessionDetails(SessionModel sessionModel)
        {
            if (sessionModel?.Session == null) return string.Empty;

            return _sessionFormattingService.FormatSessionDetails(sessionModel.Session);
        }

        /// <summary>
        /// 处理会话添加事件
        /// </summary>
        private void OnSessionAdded(Session session)
        {
            var sessionModel = ConvertToSessionModel(session);
            if (sessionModel != null)
            {
                SessionAdded?.Invoke(this, sessionModel);
            }
        }

        /// <summary>
        /// 处理会话完成事件
        /// </summary>
        private void OnSessionCompleted(Session session)
        {
            var sessionModel = ConvertToSessionModel(session);
            if (sessionModel != null)
            {
                SessionUpdated?.Invoke(this, sessionModel);
            }
        }

        /// <summary>
        /// 获取内容类型
        /// </summary>
        private string GetContentType(Session session)
        {
            var contentType = session.ResponseHeaders?["Content-Type"];
            return _dataFormattingService.SimplifyContentType(contentType);
        }

        /// <summary>
        /// 获取响应大小
        /// </summary>
        private string GetResponseSize(Session session)
        {
            if (session.ResponseBody != null)
            {
                return _dataFormattingService.FormatFileSize(session.ResponseBody.Length);
            }
            return "0 B";
        }

        /// <summary>
        /// 获取响应时间
        /// </summary>
        private string GetResponseTime(Session session)
        {
            // 获取响应时间 
            var responseTimeStr = session["responseTime"];
            // 获取请求时间
            var requestTimeStr = session["requestTime"];
            if (!string.IsNullOrEmpty(responseTimeStr) && !string.IsNullOrEmpty(requestTimeStr))
            {
                // 字符串转时间
                var responseTime = Convert.ToDateTime(responseTimeStr);
                var requestTime = Convert.ToDateTime(requestTimeStr);
                // 计算响应时间
                var totalMilliseconds = (responseTime - requestTime).TotalMilliseconds;
                return _dataFormattingService.FormatResponseTime((int)totalMilliseconds);
            }
            return "0ms";
        }

        /// <summary>
        /// 获取请求时间
        /// </summary>
        private string GetRequestTime(Session session)
        {
            // 获取请求时间
            var requestTime = session["requestTime"];
            if (!string.IsNullOrEmpty(requestTime))
            {

                // 转换格式
                return _dataFormattingService.FormatRequestTime(Convert.ToDateTime(requestTime));
            }

            return _dataFormattingService.FormatRequestTime(DateTime.Now);
        }
    }
}